//
//  LS_PictureSelectorController.swift
//  weibo
//
//  Created by 罗李苏 on 16/5/29.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SnapKit
import HMImagePicker
private let PictureCellId = "PictureCellId"
//定义显示图片的信息
private let colCount: CGFloat = 4
private let margin: CGFloat = 3
private let maxImageCount = 4
private let itemWidth: CGFloat = (ScreenWidth - (colCount + 1) * margin) / colCount


class LS_PictureSelectorController: UICollectionViewController {
    //声明图片数组
     lazy var images:[UIImage] = [UIImage]()
    //声明数组第三方框架使用
    lazy var selectedAsset: [PHAsset] = [PHAsset]()

    
    //MARK:重载构造函数
    init(){
        let layout = UICollectionViewFlowLayout()
        //设置itemSize
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //设置 行列间距
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        
        //设置每组的内边距
        layout.sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        super.init(collectionViewLayout: layout)
        //注册cell
        self.collectionView!.registerClass(LS_PictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellId)
         self.collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        return images.count + 1
        let delta = images.count == maxImageCount ? 0 : 1
        return images.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! LS_PictureSelectorCell
    
        cell.backgroundColor = randomColor()
        if indexPath.item == images.count {
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
        cell.selectorDelegate = self
        return cell
    }
}
//MARK:使用分类继承 LS_PictureSelectorCell 的协议
extension LS_PictureSelectorController: LS_PictureSelectorCellDelegate{
    func userWillAddPicture() {
        print("添加图片")
        //判断有没有 访问图片的权限
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {//群发你说明没有权限
            print("没有权限")
            return
        }
        //使用系统的图片选择器
//        //走到这里说明有权限
//        let picker = UIImagePickerController()
//        //设置代理
//        picker.delegate = self
//        //用model的方式展现 图片选择器
//        self.presentViewController(picker, animated: false, completion: nil)
        
        
        //使用第三方框架下载多图 因为借口原因 上传多张图片时只能上传到最后添加的图片 所以仅供参考
        //框架谁OC框架 所以需要 转变成swift
        /*
         HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
         
         // 设置图像选择代理
         picker.pickerDelegate = self;
         // 设置目标图片尺寸
         picker.targetSize = CGSizeMake(600, 600);
         // 设置最大选择照片数量
         picker.maxPickerCount = 9;
         
         [self presentViewController:picker animated:YES completion:nil];
         */
        
        let picker = HMImagePickerController(selectedAssets: selectedAsset)
        picker.pickerDelegate = self
        picker.targetSize = CGSizeMake(600, 600)
        picker.maxPickerCount = maxImageCount
        presentViewController(picker, animated: true, completion: nil)
        
    }
    func userWillDeletePicture(cell: LS_PictureSelectorCell) {
        print("删除图片")
        //1.删除照片(cell)需要知道操作的cell是哪一个 参数传递过来的那一个
        //2.通过cell 获取indexPath
        guard let indexPath = collectionView?.indexPathForCell(cell) else{
            return
        }
        //3.删除数组对应的数据
        images.removeAtIndex(indexPath.item)
        //刷新数据
        self.collectionView?.reloadData()
    }
}
//MARK:遵守第三方框架的协议
extension LS_PictureSelectorController:HMImagePickerControllerDelegate{
    //实现协议方法
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        //OC代码
        // 记录图像，方便在 CollectionView 显示
        //        self.images = images;
        //        // 记录选中资源集合，方便再次选择照片定位
        //        self.selectedAssets = selectedAssets;
        //
        //        [self.collectionView reloadData];
        //
        //        [self dismissViewControllerAnimated:YES completion:nil];
        
        self.images = images
        self.selectedAsset = selectedAssets!
        self.collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}
//MARK:遵守图片选择器的协议 并实现协议方法
extension LS_PictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //协议方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //把通过图片选择器选择的图片 添加奥数组中
        images.append(image)
        //刷新数据源
        self.collectionView?.reloadData()
        //实现了协议方法后 视图控制器的dismis 就只能程序员自己控制
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
//MARK:订立协议
@objc protocol LS_PictureSelectorCellDelegate: NSObjectProtocol{
    //声明协议方法
    optional func userWillAddPicture()
    optional func userWillDeletePicture(cell: LS_PictureSelectorCell)
}
class LS_PictureSelectorCell: UICollectionViewCell {
    //声明代理属性 要使用 weak 表示弱引用
    weak var selectorDelegate: LS_PictureSelectorCellDelegate?
    //声明属性
    var image: UIImage?{
        didSet{
            //完成给按钮设置图片
            //隐藏添加按钮没有图片的时候的删除按钮
        deleteBtn.hidden = image == nil
        addBtn.setImage(image, forState: .Normal)
        }
    
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @objc private func addBtnDidClick(){
//        print(#function)
        //如果按钮上已经添加了照片就不能再添加了
        if image != nil {
            return
        }
        selectorDelegate?.userWillAddPicture?()
    }
    @objc private func deleteBtnDidClick(){
//        print(#function)
        selectorDelegate?.userWillDeletePicture?(self)
    }
    
    private func setupUI(){
        //添加到父视图
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        //添加按钮的点击事件
        addBtn.addTarget(self, action: #selector(LS_PictureSelectorCell.addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(LS_PictureSelectorCell.deleteBtnDidClick), forControlEvents: .TouchUpInside)
    }
    //懒加载子控件 添加按钮
    private lazy var addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        btn.imageView?.contentMode = .ScaleAspectFill
        //裁剪父视图
        btn.imageView?.clipsToBounds = true
        return btn
    }()
    
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
                return btn
    }()

}
